package basic.study.wantOffer.chapter3;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * @ClassName Problem39
 * @Description 顺时针打印矩阵
 * @Company inspur
 * @Author Kevin
 * @Date 2020/5/15 10:56
 * @Version 1.0
 */
public class Problem29 {
    public ArrayList<Integer> printMatrixClockwisely(int[][] nums) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (nums == null) return null;
        int rows = nums.length;
        int cols = nums[0].length;
        if (rows <= 0 || cols <= 0) return null;

        int start = 0;
        while (rows > 2 * start && cols > 2 * cols) {
            PrintMatrixInCircle(list,nums, cols, rows, start);
            start++;
        }
        return list;
    }

    private void PrintMatrixInCircle(ArrayList<Integer> list, int[][] nums, int cols, int rows, int start) {
        int endX = cols -1 -start;
        int endY = rows -1 - start;

        //从左到右打印一行
        //无条件
        for (int i = start; i <= endX; i++) {
            int num = nums[start][i];
            //System.out.println(num + " ");
            list.add(num);
        }
        //从上到下打印一行
        //终止行号大于起始行号
        if (start < endY) {
            for (int i = start; i <= endY; i++) {
                int num = nums[i][endX];
                //System.out.println(num+" ");
                list.add(num);
            }
        }
        //从右到左打印一行
        //至少两行两列
        if (start < endY && start < endX) {
            for (int i = endX-1; i >= start; --i) {
                int num = nums[endY][i];
                //System.out.println(num+" ");
                list.add(num);
            }
        }
        //从下到上打印一行
        //至少三行两列
        if (start < endX && start < endY -1) {
            for (int i = endY -1; i >= start + 1; i --) {
                int num = nums[i][start];
                //System.out.println(num);
                list.add(num);
            }
        }
    }
}
